from typing import *


class Solution:
    def maximumLength(self, s: str) -> int:
        n = len(s)
        t = 0
        h = DefaultDict(Counter)
        for i, v in enumerate(s):
            t += 1
            if i < n - 1 and v != s[i + 1] or i == n - 1:
                h[v][t] += 1
                t = 0
        ans, size = -1, 0
        for k, v in h.items():
            for c, t in v.items():
                if t > 2 and c >= size:
                    ans = max(ans, c)
                    size = c
                elif c > 1 and (v[c - 1] > 0 or t > 1) and c - 1 >= size:
                    ans = max(ans, c - 1)
                    size = c - 1
                elif c > 2 and c - 2 >= size:
                    ans = max(ans, c - 2)
                    size = c - 2
        return ans


s = Solution()
print(s.maximumLength("aaaa"))
print(s.maximumLength(s="abcdef"))
print(s.maximumLength(s="abcaba"))
